package com.oceansoft.mobile.biz.api.service;

import com.alibaba.fastjson.JSON;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.Base64Utils;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.UuidUtils;
import com.oceansoft.mobile.weixin.service.WechatService;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.annotation.Resource;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lenovo on 2017/5/3.
 */
@Service
public class ApiUploadPictureServiceImpl implements  IApiUploadPictureService {
    @Resource
    private WechatService wechatService;
    /**
     * 货车临时通行证
     */
    //车辆行驶证
    public static String cltxz ="73e0e5b8-8cbb-400f-bfbb-6dec62402d71";
    //工地工程计划
    public static String gdgcjh ="f1f755d2-d9e3-4676-bc30-4a968ff2be09";
    //证明申请理由的其他材料
    public static String qtcl ="a2993d29-a438-4ff6-b096-55c282a5a359";
    /**
     * 施工车辆
     */
    //车辆行驶证
    public static String sgcltxz ="302b5540-989c-485e-93dd-6d8f332ed0c0";
    //工地工程计划
    public static String sggdgcjh ="1f702b85-56bc-406b-8ec1-7491db873bec";
    //证明申请理由的其他材料
    public static String sgqtcl ="ca5ff58a-685c-49ea-9397-8a2eb4cb49b6";
    /**
     * 律师预约
     */
    //介绍信
    public static String lacltxz ="52f9912d-4392-4325-baf6-03e2881291d5";
    //委托公函
    public static String lagdgcjh ="b5912048-c494-4d3c-b428-24e802de9ccd";
    //律师证
    public static String laqtcl ="5df2077b-725c-4635-82d5-bf063e236e5e";

   private String fileExt;

    //违法举报和咨询投诉的上传url
    public static String uploadUrl="http://172.16.1.250/e/extend/index.php?s=api/upfile";
    @Override
    public Result saveFjTX(HttpServletRequest request, String serverId, String localid, String uploadUrl) throws IOException {
        Map<String, String> param = new HashMap<>();
        String filName = null;
        filName = "fj"+localid;
      /*  InputStream is = null;
        Long m_id = new Long(String.valueOf("1056"));
        String accessToken = wechatService.getAccessToken(m_id);
        // 拼接请求地址
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        byte[] output = input2byte(is); //in_b为转换之后的结果
        // 根据内容类型获取扩展名
        String fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
        BASE64Encoder encoder = new BASE64Encoder();
        String outstr = encoder.encode(output);*/
        String outstr=getImageBase64(serverId);
        Result r=new Result();
        Map<String, String> map=new HashMap<String,String>();
        map.put("file_base64", outstr);
        map.put("file_name", filName);
        map.put("file_ext", fileExt);
        try {

            String response1= HttpClientUtil.doPost(uploadUrl, map, "utf-8");//附件上传
            JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response1));
            r=JSON.toJavaObject(josnJson,Result.class);
            String id=r.getData()+"";//附件上传之后返回的附件id
            Map<String ,String> m = (Map<String ,String>)request.getSession().getAttribute("zxjb");
            request.getSession().removeAttribute("zxjb");
            if(null==m)
            {
                m = new HashMap<String ,String>();
            }
            //m.put("xzfy_fj"+type, result);
            //将每张图的id放付Map中,根据图片名称的不同
            m.put(filName, id);
            //将图片id放入session中.
            request.getSession().setAttribute("zxjb",m);

            return r;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Result saveOneFjTX(HttpServletRequest request, String serverId, String type, String name) throws IOException {
        String imgname=name+type;
       /* Map<String, String> param = new HashMap<>();*/
       /* InputStream is = null;
        Long m_id = new Long(String.valueOf("1056"));
        String accessToken = wechatService.getAccessToken(m_id);
        // 拼接请求地址
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        byte[] output = input2byte(is); //in_b为转换之后的结果
        // 根据内容类型获取扩展名
        String fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
        BASE64Encoder encoder = new BASE64Encoder();
        String outstr = encoder.encode(output);*/
        String outstr=getImageBase64(serverId);
        String caseMatGuid = "";
        if(name.equals("hclx_fj")){
            if("1".equals(type)){
                caseMatGuid=cltxz;//,qtcl
            }else if("2".equals(type)){
                caseMatGuid=gdgcjh;//gdgcjh,
            }else if("3".equals(type)){
                caseMatGuid=qtcl;//gdgcjh,qtcl
            }
        }
        if(name.equals("sgcl_fj")){
            if("1".equals(type)){
                caseMatGuid=sgcltxz;//,qtcl
            }else if("2".equals(type)){
                caseMatGuid=sggdgcjh;//gdgcjh,
            }else if("3".equals(type)){
                caseMatGuid=sgqtcl;//gdgcjh,qtcl
            }
        }
        if("mphm_fj".equals(name)||"yzdhxp_fj".equals(name)||"items_fj".equals(name)||"xzfy_fj".equals(name)||"hkysl".equals(name)){
            caseMatGuid=type;
        }
        if(name.equals("lawyer_fj")){
            if("1".equals(type)){
                caseMatGuid=laqtcl;//,
            }else if("2".equals(type)){
                caseMatGuid=lacltxz;//gdgcjh,
            }else if("3".equals(type)){
                caseMatGuid=lagdgcjh;//gdgcjh,qtcl
            }
            name= Constant.SESSION_LAWYER_FJ;
        }

      Result result =  RequestUtils.saveFj(request,outstr,caseMatGuid, true);
        //Result result =new Result();
        Map<String , com.oceansoft.mobile.common.util.Result> m = (Map<String , com.oceansoft.mobile.common.util.Result>)request.getSession().getAttribute(name);
        request.getSession().removeAttribute(name);
        if(null==m)
        {
            m = new HashMap<String , com.oceansoft.mobile.common.util.Result>();
        }
        m.put(imgname,result);
//        System.out.println("货车附件信息==="+m.size()+"   "+m.toString());
        request.getSession().setAttribute(name,m);
        return result;
    }

    @Override
    public Result saveDogFjTX(HttpServletRequest request, String serverId, String type, String name) throws IOException {
        String imgname=name+type;
       /* InputStream is = null;
        Long m_id = new Long(String.valueOf("1056"));
        String accessToken = wechatService.getAccessToken(m_id);
        // 拼接请求地址
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        byte[] output = input2byte(is); //in_b为转换之后的结果
        // 根据内容类型获取扩展名
        String fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
        BASE64Encoder encoder = new BASE64Encoder();
        String outstr = encoder.encode(output);*/
        String outstr=getImageBase64(serverId);
        HttpSession session = request.getSession();
        session.setAttribute(imgname,outstr);
        File parentFile = new File("/files/ownerdog");
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        String courseFile = parentFile.getCanonicalPath() ;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(outstr);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {// 调整异常数据
                b[i] += 256;
            }
        }
        OutputStream out = new FileOutputStream(courseFile + "//" +  UuidUtils.getUpperUuid()+".jpeg");
        out.write(b);
        out.flush();
        out.close();
        return new Result("提交成功");


    }

    @Override
    public Result saveFZFjTX(HttpServletRequest request, String serverId) throws IOException {
        Map<String, String> param = new HashMap<>();
        String fileName="fj"+UuidUtils.getUpperUuid();
        String outstr=getImageBase64(serverId);
        byte[] content = Base64.decodeBase64(outstr.getBytes());
        Result r=new Result();
        Map<String, String> map=new HashMap<String,String>();
        map.put("fileData", outstr);
        map.put("fileName", fileName);
        map.put("fileExtension", fileExt);
        map.put("fileSize",content.length+"");
        try {
            String url=Constant.host5+"api/fztsla/SaveProjectMat";
           // String url="http://wsbsdt.szgaj.cn/interfacetest/api/fztsla/SaveProjectMat";
            String response1= HttpClientUtil.doPost(url, map, "utf-8");//附件上传
            JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response1));
            r=JSON.toJavaObject(josnJson,Result.class);
            System.out.println("======="+r.toString());
           // String id=r.getData()+"";//附件上传之后返回的附件id
            return r;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Result saveAppOneFjTx(HttpServletRequest request) throws IOException {
        String name=request.getParameter("name");
        String type=request.getParameter("type");
        String imgname=name+type;
        String outstr=request.getParameter("base64");
        System.out.println(outstr.length());
        String caseMatGuid = "";
        if(name.equals("hclx_fj")){
            if("1".equals(type)){
                caseMatGuid=cltxz;//,qtcl
            }else if("2".equals(type)){
                caseMatGuid=gdgcjh;//gdgcjh,
            }else if("3".equals(type)){
                caseMatGuid=qtcl;//gdgcjh,qtcl
            }
        }
        if(name.equals("sgcl_fj")){
            if("1".equals(type)){
                caseMatGuid=sgcltxz;//,qtcl
            }else if("2".equals(type)){
                caseMatGuid=sggdgcjh;//gdgcjh,
            }else if("3".equals(type)){
                caseMatGuid=sgqtcl;//gdgcjh,qtcl
            }
        }
        if("mphm_fj".equals(name)||"yzdhxp_fj".equals(name)||"items_fj".equals(name)||"xzfy_fj".equals(name)||"hkysl".equals(name)){
            caseMatGuid=type;
        }
        if(name.equals("lawyer_fj")){
            if("1".equals(type)){
                caseMatGuid=laqtcl;//,
            }else if("2".equals(type)){
                caseMatGuid=lacltxz;//gdgcjh,
            }else if("3".equals(type)){
                caseMatGuid=lagdgcjh;//gdgcjh,qtcl
            }
            name= Constant.SESSION_LAWYER_FJ;
        }

        Result result =  RequestUtils.saveFj(request,outstr,caseMatGuid, true);
        //Result result =new Result();
        Map<String , com.oceansoft.mobile.common.util.Result> m = (Map<String , com.oceansoft.mobile.common.util.Result>)request.getSession().getAttribute(name);
        request.getSession().removeAttribute(name);
        if(null==m)
        {
            m = new HashMap<String , com.oceansoft.mobile.common.util.Result>();
        }
        m.put(imgname,result);
//        System.out.println("货车附件信息==="+m.size()+"   "+m.toString());
        request.getSession().setAttribute(name,m);
        return result;
    }

    @Override
    public Result saveAppDogFjTx(HttpServletRequest request) throws IOException {
        String name=request.getParameter("name");
        String type=request.getParameter("type");
        System.out.println("====name"+name+"======type"+type);
        String imgname=name+type;
        String outstr=request.getParameter("base64");
        System.out.println(outstr.length());
        HttpSession session = request.getSession();
        session.setAttribute(imgname,outstr);
        File parentFile = new File("/files/ownerdog");
       /* if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        String courseFile = parentFile.getCanonicalPath() ;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(outstr);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {// 调整异常数据
                b[i] += 256;
            }
        }
        OutputStream out = new FileOutputStream(courseFile + "//" +  UuidUtils.getUpperUuid()+".jpeg");
        out.write(b);
        out.flush();
        out.close();*/
        return new Result("提交成功");
    }

    /**
     * app违法犯罪和咨询投诉上传
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public Result saveAppFjTx(HttpServletRequest request) throws IOException {
        Map<String, String> param = new HashMap<>();
        String filName = null;
        filName = "fj"+UuidUtils.getUpperUuid();
        String outstr=request.getParameter("base64");
        System.out.println("====图片base64长度："+outstr.length());
        Result r=new Result();
        Map<String, String> map=new HashMap<String,String>();
        map.put("file_base64", outstr);
        map.put("file_name", filName);
        map.put("file_ext", "jpg");
        try {

            String response1= HttpClientUtil.doPost(uploadUrl, map, "utf-8");//附件上传
            JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response1));
            r=JSON.toJavaObject(josnJson,Result.class);
            String id=r.getData()+"";//附件上传之后返回的附件id
            System.out.println("=====id:"+id);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * app法制投诉图片上传
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public Result saveAppFZFjTx(HttpServletRequest request) throws IOException {
        Map<String, String> param = new HashMap<>();
        String fileName="fj"+UuidUtils.getUpperUuid();
        String outstr=request.getParameter("base64");
        byte[] content = Base64.decodeBase64(outstr.getBytes());
        Result r=new Result();
        Map<String, String> map=new HashMap<String,String>();
        map.put("fileData", outstr);
        map.put("fileName", fileName);
        map.put("fileExtension", "jpg");
        map.put("fileSize",content.length+"");
        try {
            String url=Constant.host5+"api/fztsla/SaveProjectMat";
            //String url="http://wsbsdt.szgaj.cn/interfacetest/api/fztsla/SaveProjectMat";
            String response1= HttpClientUtil.doPost(url, map, "utf-8");//附件上传
            JSON josnJson=JSON.parseObject(StringEscapeUtils.unescapeJava(response1));
            r=JSON.toJavaObject(josnJson,Result.class);
            // String id=r.getData()+"";//附件上传之后返回的附件id
            return r;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从微信服务器上下载图片
     * @param serverId
     * @return
     * @throws IOException
     */
    private String getImageBase64(String serverId) throws IOException{
        InputStream is = null;
        String accessToken = WeixinUtil.getAccessTokenMer("1056");
        // 拼接请求地址
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        byte[] output = input2byte(is); //in_b为转换之后的结果
        // 根据内容类型获取扩展名
        String fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
        this.fileExt=fileExt;
        BASE64Encoder encoder = new BASE64Encoder();
        String outstr = encoder.encode(output);
        return outstr;
    }

    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    private String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = "jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = "mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = "amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = "mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = "mp4";
        else
            fileEndWitsh = "jpg";
        return fileEndWitsh;
    }

    private byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}
